<?php

class IndexController extends FrontendController
{
	public function actions()
	{
		return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
	}

	public function actionIndex()
	{
		$this->render('index');
	}

	public function actionLogin()
	{
		$model=Yii::app()->user->model;
        $model->setScenario('login');

        $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
            if(Yii::app()->user->loginUser($_POST['User'])){
                Yii::app()->notification->message=Yii::t('account/index','helloUser',array('{user}'=>Yii::app()->user->name));
                $this->redirect(Yii::app()->createUrl('account/index'));
            }
		}
        $this->redirect(Yii::app()->homeUrl);
	}

	public function actionLogout()
	{
        $name=Yii::app()->user->name;
        Yii::app()->user->logoutUser();
		$this->redirect(Yii::app()->createUrl('index',array('userLogoutName'=>$name)));
	}

    public function actionRegister()
    {
        $user=Yii::app()->user->model;
        $user->setScenario('register');

        $this->performAjaxValidation($user);

        if(isset($_POST['User'])){
            if(Yii::app()->user->register($_POST['User'])){
                Yii::app()->notification->message=Yii::t('account/index','helloUser',array('{user}'=>Yii::app()->user->name));
            }else{
                Yii::app()->notification->error=Yii::app()->user->message;
                $this->redirect(Yii::app()->homeUrl);
            }
            $this->redirect(Yii::app()->createUrl('account/index'));
        }
        $this->redirect(Yii::app()->homeUrl);
    }

    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && ($_POST['ajax']==='login-form' || $_POST['ajax']==='register-form')){
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}